package com.rory.gooday.common.core;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.plugin.redis.Redis;
import com.rory.gooday.common.GoodConfig;
import com.rory.gooday.common.R;
import redis.clients.jedis.params.SetParams;

/**
 * 登录拦截器
 */
public class LoginInterceptor implements Interceptor {
    /**
     * 排除url前缀
     */
    private String[] excluede;

    public LoginInterceptor(String... prefix) {
        int len = prefix.length;
        excluede = new String[len];
        for (int i = 0; i < len; i++) {
            excluede[i] = prefix[i];
        }
    }

    @Override
    public void intercept(Invocation inv) {
        // 1.比较排除前缀是否匹配,配置直接放行,
        String actionKey = inv.getActionKey();
        for (String string : excluede) {
            if (actionKey.startsWith(string)) {
                inv.invoke();
                return;
            }
        }
        Controller controller = inv.getController();
        String sid = controller.getSession().getId();
        String login = Redis.call(jedis -> jedis.get("rory"));
        if (sid.equals(login)) {
            //重新设置下线时间
            Redis.call(jedis -> {
                SetParams setParams = new SetParams();
                setParams.ex(GoodConfig.logoutime);
                return jedis.set("rory", sid,  setParams);
            });
            inv.invoke();
        }else{
            controller.renderJson(R.error());
            controller.redirect("/login");
        }
    }
}
